<!--
 * @Descripttion: 
 * @version: 
 * @Author: 尹鹏孝
 * @Date: 2021-12-10 08:48:58
 * @LastEditors: 尹鹏孝
 * @LastEditTime: 2021-12-10 09:02:25
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>二叉树层序遍历</title>
</head>

<body>
    <script>
        // 什么是层序遍历？
        // 答：从左到右一层一层遍历二叉树，它需要借助一个辅助数组来实现，队列来实现，其实就是广度优先遍历
        class Node {
            constructor(root, left, right) {
                this.root = root || null;
                this.left = left || null;
                this.right = right || null;
            }
            //设置遍历函数
            levelOrder(root) {
                let res = [], queue = [];
                queue.push(root);
                if (root === null) {
                    return res;
                }
                while (queue.length != 0) {
                    // 记录当前层节点数
                    let length = queue.length;
                    // 存放每一层的节点
                    let curLevel = [];
                    for (let i = 0; i < length; i++) {
                        let node = queue.shift();
                        curLevel.push(node.root);
                        //存放当前层下一层的节点
                        node.left && queue.push(node.left);
                        node.right && queue.push(node.right);
                    }
                    // 把每一层结果放到结果数组
                    res.push(curLevel);
                }
            }
        }


    </script>
</body>

</html>